package com.sitech.openapi.service;

import com.sitech.openapi.componet.BusiConst;
import com.sitech.openapi.componet.MapBean;
import com.sitech.openapi.componet.WSClientService;
import com.sitech.openapi.domain.ProductOrder.*;
import com.sitech.openapi.domain.customer.CAccount;
import com.sitech.openapi.domain.customer.Cust;
import com.sitech.openapi.domain.customer.CustExample;
import com.sitech.openapi.domain.user.SystemUser;
import com.sitech.openapi.domain.user.SystemUserExample;
import com.sitech.openapi.mapper.*;
import com.sitech.openapi.utils.DateUtil;
import com.sitech.openapi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    WSClientService wsClientService;
    @Autowired
    CommonMapper commonMapper;
    @Autowired
    CustMapper custMapper;
    @Autowired
    OrderCmptMapper orderCmptMapper;
    @Autowired
    SystemUserMapper systemUserMapper;
    @Autowired
    AccountMapper accountMapper;


    @Override
    public ProductOrder dealProduct(ProductOrder productOrder) {

        log.info("===============开始转2.0的新装报文===============");

        // 获取流水
        Long sequence = commonMapper.getSeq("SEQ_OUTSYSTEMACCEPT");
        String transactionId = BusiConst.PLATFORM_CRM + DateUtil.toStringYmd(DateUtil.getSysDate()) + sequence;
        log.info("业务流水—————————————————————————————" + transactionId);
        //String transactionId = productOrder.getExtCustOrderId();


        MapBean inxmlBean = new MapBean();
        String tcpCont = "ContractRoot.TcpCont.";
        MapBean tcpContBean = new MapBean();
        tcpContBean.setValue(tcpCont + "TransactionID", transactionId);
        tcpContBean.setValue(tcpCont + "ActionCode", "0");
        tcpContBean.setValue(tcpCont + "BusCode", "BC930100");
        tcpContBean.setValue(tcpCont + "ServiceCode", "SC930145");
        tcpContBean.setValue(tcpCont + "ServiceContractVer", "");
        tcpContBean.setValue(tcpCont + "ServiceLevel", "");
        tcpContBean.setValue(tcpCont + "SrcOrgID", "100000");
        tcpContBean.setValue(tcpCont + "SrcSysID", BusiConst.PLATFORM_4GWLW);
        tcpContBean.setValue(tcpCont + "SrcSysSign", "");
        tcpContBean.setValue(tcpCont + "DstOrgID", "609907");
        tcpContBean.setValue(tcpCont + "DstSysID", BusiConst.PLATFORM_CRM);
        tcpContBean.setValue(tcpCont + "ReqTime", DateUtil.toStringYmdHms(DateUtil.getSysDate()));
        tcpContBean.setValue(tcpCont + "Request.ReqType", "");
        tcpContBean.setValue(tcpCont + "Request.ReqCode", "");
        tcpContBean.setValue(tcpCont + "Request.ReqDesc", "");
        tcpContBean.setValue(tcpCont + "ReqSource", "OpenApi");// todo 这个写谁
        tcpContBean.setValue(tcpCont + "Remarks", "");

        MapBean svcBean = new MapBean();
        svcBean = getSvcBean(productOrder);
        String accNum = StringUtil.obj2Str(svcBean.getValue("SvcCont.PEB_BUSI_ORDER.PROD_INST_ACC_NBR.ACC_NBR"));

        inxmlBean.append(tcpContBean).setMapBeanByPath("ContractRoot", svcBean);
        String inxml = inxmlBean.toXML();

        log.info("拼好的入参报文信息>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + inxml);

        String url = orderCmptMapper.queryIntfParaCfgByTypeId("100201");
        log.info("调用的新装地址=====================" + url);

        String outXml = "";
        try {
            outXml = wsClientService.doQryClientSerive(inxml, url);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        // 解析反参报文，然后回填一些信息到productOrder实体
        return fillOrderInfo(outXml, productOrder,accNum);
    }

    /**
     * 根据入参拼新装的报文信息
     *
     * @param productOrder 入参
     * @return 拼好的svcContBean
     */
    private MapBean getSvcBean(ProductOrder productOrder) {

        Date currentDate = DateUtil.getSysDate();

        String createStaff = productOrder.getCreateStaff();
        String acceptRegionId = StringUtil.obj2Str(productOrder.getAcceptRegionId());
        String lanId = "";
        if (StringUtil.isNotEmptyOrNull(acceptRegionId)){
            lanId = acceptRegionId.substring(1,5);
        }
        String systemUserCode = commonMapper.getSystemUserByLanId(lanId);
        if(StringUtil.isEmptyOrNull(systemUserCode)){
            throw new RuntimeException("根据地市acceptRegionId=【"+acceptRegionId+"】未查询到配置工号信息！");
        }

        SystemUserExample systemUserExample = new SystemUserExample();
        systemUserExample.createCriteria().andSystemUserCodeEqualTo(systemUserCode);
        List<SystemUser> systemUsers = systemUserMapper.selectByExample(systemUserExample);
        SystemUser systemUser = null;
        if (systemUsers != null && systemUsers.size() > 0) {
            systemUser = systemUsers.get(0);
        } else {
            throw new RuntimeException("根据地市【"+acceptRegionId+"】配置工号【" + systemUserCode + "】未查询到工号信息！");
        }

        // 获取号码
        if (StringUtil.isEmptyOrNull(productOrder.getCustId())) {
            throw new RuntimeException("custId节点值为空！");
        }
        CustExample custExample = new CustExample();
        custExample.createCriteria().andCustIdEqualTo(productOrder.getCustId());
        List<Cust> custList = custMapper.selectByExample(custExample);
        if (custList == null || custList.size() == 0) {
            throw new RuntimeException("根据custId【" + productOrder.getCustId() + "】没有查询到客户信息！");
        }
        String accNbrType = "600";
        String accNbr = "";

        String areaId = commonMapper.getAreaId(StringUtil.obj2Str(systemUser.getCommonRegionId()));
        Long seq = commonMapper.getSeq("SEQ_WLWPRODUCT");
        accNbr = areaId.substring(1, 4) + "WLW" + seq;
        log.info("自动生成的号码——————————————————————————" + accNbr);

        String svcCont = "SvcCont.PEB_BUSI_ORDER.";
        MapBean svcContBean = new MapBean();
        String prodNbr = "";
        String productId = "";
        String offerNbr = "";
        String prodOfferId = "";
        Long serviceOfferId;
        Long ownerCustId;
        String extProdOfferInstId = "";
        String effDate = "";
        String expDate = "";
        String beginRentTime = DateUtil.toStringYmdHms(currentDate);
        String stopRentTime = "20500101125959";
        String roleCd = "";
        String accountIdStr = "";
        List<MainOfferOrderItem> mainOfferOrderItems = productOrder.getMainOfferOrderItems();
        List<AccessProdOrderItem> accessProdOrderItems = new ArrayList<>();
        if (mainOfferOrderItems != null && mainOfferOrderItems.size() > 0) {
            MainOfferOrderItem mainOfferOrderItem = mainOfferOrderItems.get(0);
            effDate = mainOfferOrderItem.getEffDate();
            expDate = mainOfferOrderItem.getExpDate();

            ownerCustId = mainOfferOrderItem.getOwnerCustId();
            offerNbr = mainOfferOrderItem.getOfferNbr();
            serviceOfferId = mainOfferOrderItem.getServiceOfferId();
            if (StringUtil.isEmptyOrNull(offerNbr)) {
                throw new RuntimeException("offerNbr为空！");
            }
            Map<String, Object> prodOfferMap = orderCmptMapper.getProdOfferByNbr(offerNbr);
            if (prodOfferMap == null) {
                throw new RuntimeException("根据销售品编码【" + offerNbr + "】未查询到销售品规格数据!");
            }
            prodOfferId = StringUtil.obj2Str(prodOfferMap.get("PROD_OFFER_ID"));
            accessProdOrderItems = mainOfferOrderItem.getAccessProdOrderItems();

            List<OrdOfferProdInstRel> ordOfferProdInstRels = mainOfferOrderItem.getOrdOfferProdInstRels();
            if (ordOfferProdInstRels != null && ordOfferProdInstRels.size() > 0) {
                roleCd = ordOfferProdInstRels.get(0).getRoleCd();
            }

        } else {
            throw new RuntimeException("MainOfferOrderItem节点为空！");
        }
        if (accessProdOrderItems != null && accessProdOrderItems.size() > 0) {
            prodNbr = accessProdOrderItems.get(0).getProdNbr();
            if (StringUtil.isEmptyOrNull(prodNbr)) {
                throw new RuntimeException("产品编码prodNbr不能为空！");
            }
            Map<String, Object> productMap = orderCmptMapper.getProductByNbr(prodNbr);
            if (productMap == null) {
                throw new RuntimeException("根据产品编码【" + prodNbr + "】未查询到产品规格数据!");
            }
            productId = StringUtil.obj2Str(productMap.get("PRODUCT_ID"));

            List<OrdProdInstAcctRel> ordProdInstAcctRels = accessProdOrderItems.get(0).getOrdProdInstAcctRels();
            if (ordProdInstAcctRels != null && ordProdInstAcctRels.size() > 0) {
                Long accountId = ordProdInstAcctRels.get(0).getAcctId();
                CAccount CAccount = accountMapper.selectByPrimaryKey(accountId);
                if (CAccount != null) {
                    accountIdStr = StringUtil.obj2Str(accountId);
                }else{
                    throw new RuntimeException("根据账户id【"+accountId+"】未查询到账户信息！");
                }
            }

        } else {
            throw new RuntimeException("AccessProdOrderItem节点为空！");
        }
        svcContBean.setValue(svcCont + "PUB_INFO.PRODUCT_ID", productId);
        svcContBean.setValue(svcCont + "PUB_INFO.PROD_OFFER_ID", prodOfferId);
        svcContBean.setValue(svcCont + "PUB_INFO.LAN_ID", systemUser.getLanId());
        svcContBean.setValue(svcCont + "PUB_INFO.COMMON_REGION_ID", systemUser.getCommonRegionId());
        svcContBean.setValue(svcCont + "PUB_INFO.CHANNEL_ID", systemUser.getChannelId());
        svcContBean.setValue(svcCont + "PUB_INFO.SYSTEM_USER_CODE", systemUserCode);
        svcContBean.setValue(svcCont + "PUB_INFO.OWNER_CUST_ID", ownerCustId);
        svcContBean.setValue(svcCont + "PUB_INFO.INSTALL_TIME_SEGMENT_ID", "");
        svcContBean.setValue(svcCont + "PUB_INFO.INSTALL_TIME", "");

        svcContBean.setValue(svcCont + "ORDER_ITEM_GROUP.SERVICE_OFFER_ID", "");
        svcContBean.setValue(svcCont + "ORDER_ITEM_GROUP.SERVICE_OFFER_NAME", "");
        svcContBean.setValue(svcCont + "ORDER_ITEM_GROUP.ACC_NBR", accNbr);
        svcContBean.setValue(svcCont + "ORDER_ITEM_GROUP.ACC_NBR_TYPE_CD", accNbrType);
        svcContBean.setValue(svcCont + "ORDER_ITEM_GROUP.DEAL_LIMIT_TIME", "");

        // 产品实例
        String prodInstStr = svcCont + "PROD_INST_LIST[0].PROD_INST.";
        svcContBean.setValue(prodInstStr + "PRODUCT_ID", productId);
        svcContBean.setValue(prodInstStr + "ADDRESS_ID", "");
        svcContBean.setValue(prodInstStr + "BEGIN_RENT_TIME", beginRentTime);
        svcContBean.setValue(prodInstStr + "STOP_RENT_TIME", stopRentTime);
        svcContBean.setValue(prodInstStr + "STATUS_CD", "130000");
        svcContBean.setValue(prodInstStr + "ADDRESS_DESC", "");

        // 销售品实例
        String offerInstList = svcCont + "PROD_OFFER_INST_LIST[0].PROD_OFFER_INST.";
        svcContBean.setValue(offerInstList + "PROD_OFFER_ID", prodOfferId);
        svcContBean.setValue(offerInstList + "STATUS_CD", "1200");
        if (StringUtil.isNotEmptyOrNull(effDate) && StringUtil.isNotEmptyOrNull(expDate)) {
            svcContBean.setValue(offerInstList + "EFF_DATE", effDate);
            svcContBean.setValue(offerInstList + "EXP_DATE", expDate);
        } else {
            effDate = DateUtil.toStringYmdHms(currentDate);
            // 合约期两年
            Date changDate = DateUtil.change(currentDate, 1, 2);
            svcContBean.setValue(offerInstList + "EFF_DATE", effDate);
            svcContBean.setValue(offerInstList + "EXP_DATE", DateUtil.toStringYmdHms(DateUtil.last(changDate, 2)));
        }

        svcContBean.setValue(offerInstList + "PROD_OFFER_ATTR_LIST", "");

        //产品销售品实例关系
        String offerProdRel = svcCont + "PROD_OFFER_INST_LIST[0].PROD_OFFER_INST.OFFER_PROD_INST_REL_LIST[0].OFFER_PROD_INST_REL.";
        svcContBean.setValue(offerProdRel + "PRODUCT_ID", productId);
        //svcContBean.setValue(offerProdRel + "ROLE_CD", roleCd);

        // 号码实例
        String prodInstAccNbr = svcCont + "PROD_INST_ACC_NBR.";
        svcContBean.setValue(prodInstAccNbr + "ACC_NBR_TYPE_CD", "600");
        svcContBean.setValue(prodInstAccNbr + "ACC_NBR", accNbr);

        // 账户实例
        String acctInfo = svcCont + "ACCT_INFO.";
        if (StringUtil.isNotEmptyOrNull(accountIdStr)) {
            svcContBean.setValue(acctInfo + "ACCT_FLAG", "1");
        } else {
            svcContBean.setValue(acctInfo + "ACCT_FLAG", "2");
        }
        svcContBean.setValue(acctInfo + "ACCOUNTT_ID", accountIdStr);

        OrderHandler orderHandler = productOrder.getOrderHandler();
        if (orderHandler != null) {
            // 经办人
            String handler = svcCont + "HANDLER.";
            svcContBean.setValue(handler + "CERT_NBR", orderHandler.getCertNum());
            svcContBean.setValue(handler + "CERT_TYPE", orderHandler.getCertType());
            svcContBean.setValue(handler + "HANDLE_PEOPLE_NAME", orderHandler.getHandler());
            if(StringUtil.isNotEmptyOrNull(orderHandler.getHandlerPhone())){
                svcContBean.setValue(handler + "CONTACT_NBR", orderHandler.getHandlerPhone());
            }else{
                svcContBean.setValue(handler + "CONTACT_NBR", "0");
            }
        }
        log.info("svcBean=========================" + svcContBean.toXML());
        return svcContBean;
    }

    /**
     * 根据返回的订单信息，查询表然后回填一些实例信息
     *
     * @param outXml       反参报文
     * @param productOrder 入参实体
     * @return 回填后的实体
     */
    private ProductOrder fillOrderInfo(String outXml, ProductOrder productOrder,String accNum) {

        MapBean mapBean = new MapBean();
        mapBean.fromXML(outXml);
        String rspCode = StringUtil.obj2Str(mapBean.getValue("ContractRoot.TcpCont.Response.RspCode"));
        if (Objects.equals(rspCode, "0000")) {
            String str = "ContractRoot.SvcCont.PEB_BUSI_ORDER.";
            String custOrderId = StringUtil.obj2Str(mapBean.getValue(str + "CUST_ORDER_ID"));
            String prodOfferInstId = StringUtil.obj2Str(mapBean.getValue(str + "PROD_OFFER_INST_ID"));
            String prodInstId = StringUtil.obj2Str(mapBean.getValue(str + "PROD_INST_ID"));

            productOrder.setCustOrderId(Long.parseLong(custOrderId));
            MainOfferOrderItem mainOfferOrderItem = productOrder.getMainOfferOrderItems().get(0);
            mainOfferOrderItem.setCustOrderId(Long.parseLong(custOrderId));
            mainOfferOrderItem.setOfferInstId(Long.parseLong(prodOfferInstId));

            AccessProdOrderItem accessProdOrderItem = mainOfferOrderItem.getAccessProdOrderItems().get(0);
            accessProdOrderItem.setProdInstId(Long.parseLong(prodInstId));
            accessProdOrderItem.setAccNum(accNum);

            OrdOfferProdInstRel ordOfferProdInstRel = mainOfferOrderItem.getOrdOfferProdInstRels().get(0);
            ordOfferProdInstRel.setProdInstId(Long.parseLong(prodInstId));

        } else {
            throw new RuntimeException(StringUtil.obj2Str(mapBean.getValue("ContractRoot.TcpCont.Response.RspDesc")));
        }

        return productOrder;
    }
}
